<template>
  <div>
    <!-- ref="form"  -->
    <el-form :model="spuForm" label-width="100px">
      <el-form-item label="SPU名称">
        <el-input v-model="spuForm.spuName" placeholder='SPU名称'></el-input>
      </el-form-item>
      <el-form-item label="品牌">
        <el-select v-model="spuForm.tmId" placeholder="请选择品牌">
          <el-option :label="tm.tmName" :value="tm.id" v-for="(tm,index) in trademarkList" :key="tm.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input type="textarea" v-model="spuForm.description" rows="4"></el-input>
      </el-form-item>
      <el-form-item label="SPU图片">
        <!--      照片墙 -->
        <el-upload
          action="/dev-api/admin/product/fileUpload"
          list-type="picture-card"
          :file-list="spuImageList"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt=""/>
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select v-model="saleAttrIdName"
                   :placeholder="unUsedSaleAttrList.length>0?`还有${unUsedSaleAttrList.length}个未选择`:'没有啦!!'">
          <el-option :label="unUsedSaleAttr.name" :value="`${unUsedSaleAttr.id}:${unUsedSaleAttr.name}`"
                     v-for="(unUsedSaleAttr,index) in unUsedSaleAttrList" :key="unUsedSaleAttr.id"></el-option>
        </el-select>
        <el-button type="primary" @click="addSaleAttr" :disabled="!saleAttrIdName">添加销售属性</el-button>
        <el-table
          :data="spuForm.spuSaleAttrList"
          style="width: 100%" border>
          <el-table-column
            prop="prop"
            align="center"
            type="index"
            label="序号"
            width="80">
          </el-table-column>
          <el-table-column
            prop="saleAttrName"
            label="属性名"
            width="150">
          </el-table-column>
          <el-table-column
            prop="prop"
            label="属性名称列表"
            width="width">
            <template slot-scope="{row,$index}">
              <el-tag
                type="success"
                size="mini"
                closable
                :disable-transitions="false"
                v-for="(saleAttrValue,index) in row.spuSaleAttrValueList"
                :key="saleAttrValue.id"
                @close="row.spuSaleAttrValueList.splice(index,1)"
              >{{ saleAttrValue.saleAttrValueName }}
              </el-tag>
              <!-- v-model="row.inputValue" 就算这个属性不存在，用户只要输入了东西，这个属性就会自动创建并且响应式 -->
              <el-input
                class="input-new-tag"
                v-if="row.inputVisible"
                v-model="row.saleAttrValueName"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="toButton(row)"
                @blur="toButton(row)"
              >
              </el-input>
              <el-button v-else class="button-new-tag" size="small" @click="toInput(row)">+添加</el-button>
            </template>
          </el-table-column>
          <el-table-column
            prop="prop"
            label="操作"
            width="150">
            <template slot-scope="{row,$index}">
              <HintButton
                type="danger"
                size="mini"
                icon="el-icon-delete"
                title="删除" slot="reference"
                @click="spuForm.spuSaleAttrList.splice($index,1)">
              </HintButton>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="save">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>

    </el-form>
  </div>
</template>

<script>
export default {
  name: "SpuForm",
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,//打开dialog对话框

      saleAttrIdName: '',
      /*inputVisible: false,//input框的相关初始值   不一定用先写在这里
      inputValue: '',//input框的相关初始值   不一定用先写在这里*/
      spuForm: {
        category3Id: 0,
        description: "",
        tmId: "",
        spuName: "",
        spuImageList: [
          /*{
            "imgName": "string",
            "imgUrl": "string",
          }*/
        ],
        spuSaleAttrList: [
          /*   {
               "baseSaleAttrId": 0,
               "saleAttrName": "",
               "spuSaleAttrValueList": [
                 {
                   "baseSaleAttrId": 0,
                   "isChecked": "",
                   "saleAttrName": "",
                   "saleAttrValueName": "",
                 }
               ]
              }*/
        ],
      },
      category3Id: '',
      spuImageList: [],//请求初始化的spu图片列表
      trademarkList: [],//请求初始化的所有品牌列表
      baseSaleAttrList: [],//请求初始化的所有的销售属性列表
    }
  },
  methods: {
    //照片墙相关的
    handleRemove(file, fileList) {
      /*  console.log(file, fileList);*/
      this.spuImageList = fileList
    },
    //照片墙相关的
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleSuccess(response, file, fileList) {
      /* console.log(response, file, fileList)*/
      this.spuImageList = fileList
    },
    //这个函数是初始化函数用的 1
    async getInitUpdateSpuFormData(row, category3Id) {
      this.category3Id = category3Id
      //http://localhost:9529/dev-api/admin/product/getSpuById/1914
      const result1 = await this.$API.spu.get(row.id)
      if (result1.code === 200 || result1.code === 20000) {
        this.spuForm = result1.data
      }

      // http://localhost:9529/dev-api/admin/product/spuImageList/1914
      const result2 = await this.$API.sku.getSpuImageList(row.id)
      if (result2.code === 200 || result2.code === 20000) {
        let spuImageList = result2.data
        spuImageList.forEach(item => {
          item.name = item.imgName
          item.url = item.imgUrl
        })
        this.spuImageList = spuImageList
      }
//http://localhost:9529/dev-api/admin/product/baseTrademark/getTrademarkList
      const result3 = await this.$API.trademark.getList()
      if (result3.code === 200 || result3.code === 20000) {
        this.trademarkList = result3.data
      }
      //http://localhost:9529/dev-api/admin/product/baseSaleAttrList
      const result4 = await this.$API.spu.getSaleAttrList()
      if (result4.code === 200 || result4.code === 20000) {
        this.baseSaleAttrList = result4.data
      }
    },
    //这个函数是初始化函数用的 2
    async getInitAddSpuFormData(category3Id) {
      this.category3Id = category3Id
//http://localhost:9529/dev-api/admin/product/baseTrademark/getTrademarkList
      const result3 = await this.$API.trademark.getList()
      if (result3.code === 200 || result3.code === 20000) {
        this.trademarkList = result3.data
      }
      //http://localhost:9529/dev-api/admin/product/baseSaleAttrList
      const result4 = await this.$API.spu.getSaleAttrList()
      if (result4.code === 200 || result4.code === 20000) {
        this.baseSaleAttrList = result4.data
      }
    },
    //添加销售属性
    addSaleAttr() {
      //当点击添加销售属性 通过刚才选择select收集到的数据 获取收集到的销售属性的id和name
      let [baseSaleAttrId, saleAttrName] = this.saleAttrIdName.split(':')
      let obj = {
        baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueList: []
      }
      this.spuForm.spuSaleAttrList.push(obj)
      this.saleAttrIdName = ""//清空选择的输入框
    },
    //点击button切换成input
    toInput(row) {
      //添加saleAttrValueName 和inputVisible 两个响应式的属性
      this.$set(row, 'inputVisible', true)
      this.$set(row, 'saleAttrValueName', "")
      //自动获取焦点
      this.$nextTick(() => {
        this.$refs.saveTagInput.focus()
      });
    },
    //input失去焦点，把刚才收集的用户输入的数据，获取到，变为一个对象，添加到row.spuSaleAttrValueList当中
    //点击input 变成button
    toButton(row) {
      let {baseSaleAttrId, saleAttrValueName} = row
      let obj = {baseSaleAttrId, saleAttrValueName}
      if (saleAttrValueName.trim() === '') {
        row.saleAttrValueName = ''//清空输入框
        row.inputVisible = false//变成button
        return
      }
      //输入的内容是否重复
      let isRepeat = row.spuSaleAttrValueList.some(item => {
        return item.saleAttrValueName === saleAttrValueName
      })
      if (isRepeat) {
        this.$message.success('属性是不能重复')
        row.saleAttrValueName = ''
        return;
      }
      row.spuSaleAttrValueList.push(obj)
      row.inputVisible = false; //切换为button
      row.saleAttrValueName = '';//清空输入框
    },
    //点击保存按钮
    async save() {
      //获取参数
      let {spuForm, spuImageList, category3Id} = this
      //整理参数
      //1.整理图片的数据结构
      //2.整理category3Id
      //3.去掉所有销售属性身上不需要的属性
      spuForm.category3Id = category3Id
      //整理要求的图片结构
      // {
      //   imgName: "string",
      //   imgUrl: "string",
      // },
      //目前我们的图片列表数据结构，前面已经说过
      //包含之前已经有的和自己最近上传的
      //之前已经有的图片内部是有imgName和imgUrl,它也有name和url,而自己上传的只有name和url（错的）
      // map方法是会根据老的数组生成一个新的数组，新的数组内部每一项和对应的老数组每一项有关系
      spuForm.spuImageList = spuImageList.map(item => {
        return {
          imgName: item.name,
          imgUrl: item.imgUrl || item.response.data //(自己新上传的图片路径)
        }
      })
      spuForm.spuSaleAttrList.forEach(item => {
        delete item.inputVisible
        delete item.saleAttrValueName
      })
      //发请求
      try {
        const result = await this.$API.spu.addUpdate(spuForm)
        if (result.code === 200 || result.code === 20000) {
          //成功
          this.$message.success('保存成功')//1.提示
          this.$emit('update:visible', false)//返回父组件的列表页
          this.$emit('backSuccess')//在一次触发自定义事件 告诉父组件回来 删除flag
          this.resetData()//清空data中的数据  data初始化
        }
      } catch (error) {
        //失败
        this.$message.error('保存请求失败')
      }
    },
    //清空data中的数据
    resetData() {
        this.dialogImageUrl = '',
        this.dialogVisible = false,//打开dialog对话框
        this.saleAttrIdName = '',
        this.spuForm = {
          category3Id: 0,
          description: "",
          tmId: "",
          spuName: "",
          spuImageList: [],
          spuSaleAttrList: []
        },
         this.category3Id='',
        this.spuImageList= [],//请求初始化的spu图片列表
        this.trademarkList=[],//请求初始化的所有品牌列表
        this.baseSaleAttrList= []//请求初始化的所有的销售属性列表
    },
    //点击取消按钮
    cancel(){
      //返回父组件
      this.$emit('update:visible',false)//切换到父组件的列表页
      this.$emit('cancelBack')//触发一次自定义事件,告诉父组件回来了 清空标志位
      this.resetData()//清空输入框
    }
  },
  computed: {
    //计算属性 未选择的属性
    unUsedSaleAttrList() {
      //从总的销售属性中过滤.和小的列表当中每一个名字都不一样的项
      /*  return this.baseSaleAttrList.filter(item=>{
         return  this.spuForm.spuSaleAttrList.every(item1=>{
         return item1.saleAttrName!==item.name
         })
       })*/
      return this.baseSaleAttrList.filter((item) =>
        this.spuForm.spuSaleAttrList.every(
          (item1) => item.name !== item1.saleAttrName
        )
      );
    }
  }
}
</script>

<style>
.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
